package user

import (
	"context"
	"github.com/jinzhu/copier"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/api/constans"
	"go-zero-project/services/user/rpc/pb"
	"strings"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
	// 1. check AuthCode
	stringCmd := l.svcCtx.RedisClient.Get(l.ctx, constans.CaptchaRedisKeyPrefix+req.CaptchaId)
	if stringCmd.Err() != nil {
		logx.Errorf("get CaptchaRedisKeyPrefix redis err:", stringCmd.Err())
		return nil, excption.NewErrCode(constans.CaptchaCodeErr)
	}
	if !strings.EqualFold(stringCmd.Val(), req.AuthCode) {
		logx.Errorf("captcha auth error：%s", "验证码输入错误!")
		return nil, excption.NewErrCode(constans.CaptchaCodeErr)
	}
	// 2.builder rpc request
	loginReq := pb.LoginReq{Username: req.Username, Password: req.Password}
	// 3.request rpc
	loginResp, err := l.svcCtx.UserCenterClient.Login(l.ctx, &loginReq)
	if err != nil {
		logx.Errorf("request user-rpc error：%s", err.Error())
		return nil, err
	}
	// 4.return obj
	resp = new(types.LoginResp)
	copyErr := copier.Copy(resp, loginResp)
	if copyErr != nil {
		return nil, copyErr
	}
	return resp, nil
}
